<script setup lang="ts">
import { Upload } from '@element-plus/icons-vue'
import {ref, onMounted, computed,toRefs,reactive } from "vue";
import * as Api from '@/api/homework'
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import hm from '@/components/hm.vue';
let isAdd = ref(true)
interface User {
  date: string
  name: string
  address: string
}
const ishw = ref(false)
const type = ref("0")
const classid = ref()
const buzhi =async ()=>{
  ishw.value = true
  dialogVisible.value = false
  let result = await Api.gettype(type.value)
  if (result.code === 200){
      tableData1.value = result.data
  }
}
const tableData =ref([])
let total = ref(0)
let pageSize = ref(25)
let currentPage = ref(1)
let title = ref('')
import * as echarts from "echarts";
const getData =async ()=> {
  let result = await Api.page({
    "currentPage": currentPage.value,
    "pageSize": pageSize.value,
    "title":title.value
  })
  if (result.code === 200){
    tableData.value = result.data.rows
    total.value = result.data.total
  }
}
const over =async (id)=>{
   let result =  await Api.compleated({
    "homeworkId":id
  })
  if (result.code === 200){
    return  result.data
  }
}
const fetchCompletedCounts = async () => {
  for (const item of tableData.value) {
    try {
      const completedCount = await over(Number(item.id)); // 等待并获取完成人数
      if (completedCount !== null) {
        item.completedCount = completedCount; // 更新item的completedCount属性
      } else {
        item.completedCount = '加载中...'; // 或者设置为其他默认值，表示加载失败或未获取到数据
      }
    } catch (error) {
      console.error('Error updating completed count for item ID:', item.id, error);
      item.completedCount = '加载中...'; // 或者设置为错误提示信息
    }
  }
};
const handleCurrentChange = (e) => {
  currentPage.value = e
  getData()
}
const handleSizeChange = (e)=>{
  pageSize.value = e
  getData()
}
const optionclass = ref([])
const classl =async ()=>{
  let result = await Api.listclass()
  if (result.code === 200){
    optionclass.value = result.data
  }
  else {
    alert("获取班级信息出错啦")
  }
}
onMounted(async () => {
  await getData()
  await fetchCompletedCounts();
})
const shuaxin =async ()=> {
  title.value='';
  let result = await Api.page({
    "title":'',
  })
  if (result.code === 200){
    tableData.value = result.data.rows
  }
}
const content = ref('')
//add
const form = ref({
  id :'',
  title :'',
  type:'',
  dueDate: '',
  questionId: '',
  classId: '',
})
const dialogVisible = ref(false)
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('您确定取消操作?')
      .then(() => {
        done()
        // isAdd.value = true
        // tableData2.value=[""]
      })
      .catch(() => {
        // catch error
      })
}
const btuAdd = async ()=> {
  await classl()
  dialogVisible.value=true
  isAdd.value = true
  tableData2.value = []
  form.value.title= ""
  form.value.questionId= ""
  form.value.type=""
  form.value.dueDate= ""
  form.value.classId=""
}
const add = async () => {
  let result = await Api.add({
    "title":form.value.title,
    "questionId": content.value,
    "type":form.value.type,
    "dueDate":form.value.dueDate,
    "classId":classid.value.join(",")
  })
  if(result.code === 200){
    await getData()
    await fetchCompletedCounts()
    dialogVisible.value=false
    ElMessage.success(result.message)
  }else {
    ElMessage.error(result.message)
  }
}
// 提取重置逻辑
const resetFormState = () => {
  form.value = {
    id: '',
    title: '',
    questionId: '',
    dueDate: '',
    type: '',
    classId: ''
  }
}
const update = async (id) => {
  let loadingInstance = null // 先声明loading实例

  try {
    // 1. 显示加载状态
    loadingInstance = ElLoading.service({
      lock: true,
      text: '数据提交中...',
      background: 'rgba(0, 0, 0, 0.5)'
    })

    // 2. 准备提交数据
    const { id: formId, title, questionId, dueDate, type, classId } = form.value

    // 3. 调用API
    const result = await Api.update(id, {
      id: formId,
      title,
      questionId,
      dueDate,
      type,
      classId
    })

    // 4. 处理结果
    if (result.code === 200) {
      ElMessage.success(result.message || '更新成功')

      // 5. 刷新数据并重置表单
      await getData()
      await fetchCompletedCounts()
      await resetFormState()
      // 6. 关闭对话框
      dialogVisible.value = false
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('更新操作异常:', error)
    ElMessage.error(error.message || '请求异常，请稍后重试')
  } finally {
    // 7. 确保关闭加载状态
    if (loadingInstance) {
      loadingInstance.close()
    }

    // 8. 重置状态
    isAdd.value = true
    tableData2.value = [] // 使用空数组更规范
  }
}
async function fetchData(numberArray) {
  tableData2.value = []
  try {
    for (const item of numberArray.value) {
      console.log(item);
      const result = await Api.getq(item); // 等待异步函数完成
      if (result && result.data) { // 检查 result 和 result.data 是否存在
        tableData2.value.push(result.data); // 将数据推入数组
      } else {
        console.error(`No data returned for item: ${item}`);
      }
    }
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
const btuUpdate = async (data)=> {
  isAdd.value = false
  dialogVisible.value=true
  form.value.id = data.id
  console.log("作业id"+form.value.id)
  form.value.title = data.title
  form.value.questionId = data.questionId
  form.value.dueDate = data.dueDate
  form.value.type = data.type
  form.value.classId = data.classId
  // 处理班级多选回显
  if (data.classId) {
    // 情况1：classId是字符串如 "1,2,3"
    if (typeof data.classId === 'string') {
      classid.value = data.classId.split(',').map(id => Number(id)) // 确保转为数字
    }
    // 情况2：classId是数组如 [1, 2, 3]
    else if (Array.isArray(data.classId)) {
      classid.value = data.classId.map(id => Number(id)) // 确保转为数字
    }
    // 其他情况置空
    else {
      classid.value = []
    }
  } else {
    classid.value = []
  }

  console.log('当前选中班级:', classid.value)

  const question = data.questionId
  const numberArray = ref(question.split(",").map(Number));
  await fetchData(numberArray)
}
const submit = ()=> {
  if (isAdd.value) {
    add()
  } else {
    update(form.value.id)
  }
}
const dele = async (id) => {
  console.log(id);
  await ElMessageBox.confirm('您确定要删除吗', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    let result = await Api.dele(id)
    if (result.code === 200) {
      getData()
      ElMessage.success(result.message)
    } else {
      ElMessage.error(result.message)
    }
  })
}
interface User {
  id: number
  date: string
  name: string
  address: string
  title: string
  content: string
}
const isfenxi = ref(false)
const fanhui = ()=> {
  isfenxi.value = false
}
import { ElTable } from 'element-plus'
interface User {
  date: string
  name: string
  address: string
}
const tableData1 =ref([])
const optiontype = [
  {
    value: '0',
    label: '写作',
  },
  {
    value: '2',
    label: '阅读a',
  },
  {
    value: '3',
    label: '阅读b',
  },
  {
    value: '4',
    label: '阅读c',
  },
  {
    value: '5',
    label: '翻译',
  },
]
const findtype =async ()=>{
  let result = await Api.gettype(type.value)
  if (result.code === 200){
    tableData1.value = result.data
  }
}
const selectedRows = ref([]);
const selectedRowKeys = ref([]);
console.log(selectedRows)
console.log(selectedRowKeys)
const tableData2 = ref([]);
const addedRowIds = reactive(new Set());
const handleSelectionChange = (val) => {
  val.forEach(row => {
    // 如果这行还没有被添加到 tableData2，则添加它
    if (!addedRowIds.has(row.id)) {
      tableData2.value.push({...row}); // 使用 {...row} 创建行的浅拷贝
      addedRowIds.add(row.id); // 将行的 ID 添加到已添加集合中
      content.value = tableData2.value.map(row => row.id).join(',');
    }
  });
}
const removeFromTarget = (id) => {
  tableData2.value = tableData2.value.filter(row => row.id !== id);
  addedRowIds.delete(id); // 同时从已添加集合中移除该行的 ID
};
  const addtm = async () => {
    await ElMessageBox.confirm('您确定要添加这些题目吗', '温馨提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    }).then(async () => {
      ishw.value = false
      dialogVisible.value = true
    })
  }
  const fanhuibuzhi = async () => {
    await ElMessageBox.confirm('您确定要返回吗', '温馨提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    }).then(async () => {
      ishw.value = false
      dialogVisible.value = true
    })
  }
const drawer = ref(false)
const options1 = [
  {
    value: '1',
    label: '作业',
  },
  {
    value: '2',
    label: '模拟卷',
  },
  {
    value: '3',
    label: '专项训练',
  },
]
const tableDatasTwo = ref([])
const tableDatasOne = ref([])
const homeworkId = ref('');
const childComponentRef = ref(null);
const numberArray = ref([]);

const fetchQuestionData = async (id) => {
  try {
    const res = await Api.getq(id);
    return res.data; // 假设返回 { type: 1/2/3/4 }
  } catch (error) {
    console.error('获取题目类型失败:', error);
    return null;
  }
};

// 获取题目正确数据
const fetchQuestionStats = async (homeworkId, questionId,xquestionId) => {
  try {
    const [rightRes, accuracyRes] = await Promise.all([
      Api.rightsum({
        "homeworkId": homeworkId,
        "questionId": questionId,
        "xquestionId" : xquestionId,
      }),
      Api.accuracy({
        "shomeworkId": homeworkId,
        "squestionId": questionId,
        "xquestionId" : xquestionId,
        "questionId": questionId,
        "homeworkId": homeworkId,
      })
    ]);
    const rightCount = rightRes.data || 0;
    // 当答对人数为0时，强制正确率为0
    const accuracy = rightCount === 0 ? 0 : (accuracyRes.data || 0);

    return {
      right: rightCount,
      accuracy: accuracy
    };
  } catch (error) {
    console.error('获取题目统计失败:', error);
    return { right: 0, accuracy: 0 };
  }
};

// 处理题目ID变化
const processQuestions = async (ids) => {
  if (!ids || !homeworkId.value) return;

  numberArray.value = ids.split(",").map(Number);
  tableDatasOne.value = []; // 清空旧数据

  for (const id of numberArray.value) {
    const question = await fetchQuestionData(id);
    if (!question) continue;

    let loopTimes = 0;
    switch(question.type) {
      case 1: loopTimes = 25; break;
      case 2:
      case 3: loopTimes = 10; break;
      case 4: loopTimes = 5; break;
      default: continue;
    }

    for (let i = 1; i <= loopTimes; i++) {
      const stats = await fetchQuestionStats(homeworkId.value, id,i);
      tableDatasOne.value.push({
        date: `${id}-${i}`, // 题号
        peo: stats.right, // 答对人数
        right: stats.accuracy // 正确率
      });
    }
  }

  // 更新子组件数据
  if (childComponentRef.value) {
    childComponentRef.value.updateData(tableDatasOne.value);
  }
};




const lookfx = async (data)=> {
  drawer.value = true
  const ids = data.questionId
  homeworkId.value = data.id
  const classId = data.classId
  const idClassArray = ref(classId.split(",").map(Number));
  try {
    // 首先获取所有班级的学生数据
    const studentPromises = idClassArray.value.map(classId => Api.findclass(classId).then(result => {
      if (result.code === 200) {
        return result.data; // 假设result.data是学生数组
      } else {
        throw new Error(`请求班级ID ${classId} 失败，状态码：${result.code}`);
      }
    }));

    const allStudents = await Promise.all(studentPromises);
    const flatStudents = allStudents.flat(); // 将二维数组转换为一维数组

    // 创建一个数组来存储带有成绩的学生数据
    const studentsWithScores = [];

    // 对每个学生获取成绩，并添加到studentsWithScores数组中
    for (const student of flatStudents) {
      try {
        const scoreResult = await Api.score({
          "stuId": student.id,
          "homeworkId": homeworkId.value
        }); // 假设Api有findscore方法来获取成绩
        if (scoreResult.code === 200) {
          studentsWithScores.push({...student, score: scoreResult.data}); // 假设scoreResult.data是成绩
        } else {
          // 处理获取成绩失败的情况
          console.error(`获取学生ID ${student.id} 的成绩失败，状态码：${scoreResult.code}`);
          // 可以选择添加没有成绩的学生数据，或者跳过该学生
          studentsWithScores.push({...student, score: null}); // 这里选择添加但没有成绩
        }
      } catch (scoreError) {
        // 处理获取成绩时发生的任何错误
        console.error(`获取学生ID ${student.id} 的成绩时发生错误：`, scoreError);
        studentsWithScores.push({...student, score: null}); // 添加但没有成绩
      }
    }
    // 更新表格数据
    tableDatasTwo.value = studentsWithScores;
    console.log(tableDatasTwo.value)
  } catch (error) {
    console.error('请求过程中发生错误：', error);
    // 在这里添加额外的错误处理逻辑
  }
  await processQuestions(ids);
}


  // const numberArray = ref(ids.split(",").map(Number));//题目号
  // 获取题目数据

// 题型切换回调方法
const handleTypeChange = (selectedValue) => {
  console.log('当前选中题型值:', selectedValue)
  console.log('当前响应式变量值:', type.value)
  findtype()
  // 调用您的业务方法

}
</script>

<template>
  <div v-show="!ishw"  style="position: absolute;top: 100px;width: 90%;height: 40px;border-bottom: solid 1px rgb(221.7, 222.6, 224.4);margin: auto">
    <el-row>
      <el-col :span="8">
        <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 150px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);"@click="btuAdd">
          布置作业<el-icon class="el-icon--right"><Upload /></el-icon>
        </el-button>
        <div class="grid-content ep-bg-purple" />
      </el-col>
      <el-col :span="10">
        <div class="grid-content ep-bg-purple-light" />
      </el-col>
      <el-col :span="6">
        <el-input
            v-model="title"
            style="width: 200px;padding-left: 5px;border-radius: 20px ;margin-right: 5px"
            placeholder="请输入名称"
        />
        <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 20px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);" @click="getData()">
          <el-icon class="el-icon--right"><el-icon><Search /></el-icon></el-icon>
        </el-button>
        <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 20px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);" @click="shuaxin">
          <el-icon ><el-icon><RefreshRight /></el-icon></el-icon>
        </el-button>
        <div class="grid-content ep-bg-purple" />
      </el-col>
    </el-row>
  </div>
    <div v-show="!ishw" style="height: 88%;width: 100%;margin-top: 80px">
      <el-table
          :data="tableData"
          :default-sort="{ prop: 'createTime', order: 'descending' }"
          style="width: 100%;height: 95%"
      >
        <el-table-column prop="id" label="编号" width="120" />
        <el-table-column prop="title" label="标题" width="180" />
        <el-table-column prop="classId" label="发布班级" width="120" />
        <el-table-column prop="questionId" label="题号" width="120" />
        <el-table-column prop="createTime" label="发布时间" width="220" />
        <el-table-column prop="dueDate" label="截止时间" width="220" />
        <el-table-column label="完成人数" width="180">
          <template #default="scope">
            <span v-if="scope.row.completedCount !== null">{{ scope.row.completedCount }}</span>
            <span v-else>加载中...</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button
                link
                size="small"
                style="color: #4285F4"
                @click="btuUpdate(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                link
                size="small"
                style="color: #4285F4"
                @click="lookfx(scope.row)"
            >
             查看分析
            </el-button>
            <el-button
                link
                size="small"
                style="color: #4285F4"
                @click="dele(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination      :title="isAdd ? '新增:' : '修改:'"
      width="80%"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[25, 50, 100, 200]"

      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 10px"
  />
  </div>
  <div v-show="isfenxi" style="background-color:pink;width: 100%;height: 100%">
    <el-button style="border: solid 1px #4285F4;position: absolute;right: 10px;top: 60px;border-radius: 20px;width: 150px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);"@click="fanhui()">
      返回
    </el-button>


  </div>

<!--添加题目对话框-->

  <el-dialog
      v-model="dialogVisible"

      style="height: 650px;"
      :before-close="handleClose"
  >
      <span>
        <el-form :inline="true" :model="form" class="demo-form-inline">
    <el-form-item label="作业标题：">
      <el-input v-model="form.title" placeholder=""  />
    </el-form-item>
          <el-form-item label="作业类型：">
      <el-select
          v-model="form.type"
          placeholder="请选择"
          size="default"
          style="width: 260px;height: 20px;min-height: 20px;margin-right: 5px;margin-bottom: 15px"
      >
          <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
    </el-form-item>
          <el-form-item label="班级：">
      <el-select
          v-model="classid"
          multiple
          placeholder="请选择班级"
          style="width: 240px"
      >
      <el-option
          v-for="item in optionclass"
          :key="item.id"
          :label="item.name"
          :value="item.id"
      />
    </el-select>
    </el-form-item>
    <el-form-item label="截止时间：">
      <el-date-picker
          v-model="form.dueDate"
          type="date"
          placeholder="请选择截止时间"
          clearable
          value-format="YYYY-MM-DDTHH:mm:ss"
      />
    </el-form-item>
  </el-form>
   <el-table
       :data="tableData2"
       row-key="id"
       height="440"
       style="width: 100%; margin-top: 20px;"
   >
      <el-table-column label="题号" prop="id" />
      <el-table-column label="试卷名称" prop="title" />
     <el-table-column align="right">
      <template #header >
         <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 150px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);"@click="buzhi">
          添加题目
        </el-button>
        <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 150px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);"@click="submit()">
          布置作业
        </el-button>
      </template>
       <el-table-column type="expand" width="400">
          <template #default="props" >
            <div m="4">
              <h2>题目：</h2>
              {{ props.row.content }}
            </div>
          </template>
        </el-table-column>
<!--      <template #default="props">-->
<!--            <el-button @click="removeFromTarget(props.row.id)">移除</el-button>-->
<!--      </template>-->
    </el-table-column>
    </el-table>
      </span>
  </el-dialog>

  <!--  题目选择-->

    <div v-show="ishw" style="height: 100%">
      <el-row>
        <el-col :span="8">
          <div class="grid-content ep-bg-purple" />
        </el-col>
        <el-col :span="6">
          <div class="grid-content ep-bg-purple-light" />
        </el-col>
        <el-col :span="10">
          <el-select
              v-model="type"
              placeholder="题型："
              size="default"
              style="width: 180px;height: 20px;min-height: 30px;margin-left:150px"
              @change="handleTypeChange"
          >
            <el-option
                v-for="item in optiontype"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <el-button style="border: solid 1px #4285F4;border-radius: 20px;margin-left: 10px;width: 20px;color: #4285F4;background-color:rgb(216.8, 235.6, 255); "@click="findtype()">
            <el-icon class="el-icon--right"  ><el-icon ><Search /></el-icon></el-icon>
          </el-button>
          <el-button @click="addtm" style="border: solid 1px #4285F4;border-radius: 20px;margin-left: 10px;width:80px;color: #4285F4;background-color:rgb(216.8, 235.6, 255); ">
            <el-icon class="el-icon--right"  ><el-icon><Select /></el-icon>添加</el-icon>
          </el-button>
          <el-button style="border: solid 1px #4285F4;border-radius: 20px;margin-left: 10px;width:80px;color: #4285F4;background-color:rgb(216.8, 235.6, 255); ">
            <el-icon @click="fanhuibuzhi" class="el-icon--right"  >返回</el-icon>
          </el-button>

          <div class="grid-content ep-bg-purple" />
        </el-col>
      </el-row>
      <el-table :data="tableData1" @selection-change="handleSelectionChange"
                ref="multipleTable"
                stripe
                row-key="id"
                style="width: 100%;margin-top: 20px;height: 500px">
        <el-table-column
            type="selection"
            width="55"
        />
        <el-table-column type="expand">
          <template #default="props">
            <div m="4">
              <h2>题目：</h2>
              {{ props.row.content }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="编码" prop="id" />
        <el-table-column label="试卷名称" prop="title" />
      </el-table>
    </div>


<!-- 数据分析 -->
  <el-drawer v-model="drawer"  :with-header="false" size="50%">
    <hm :tableDataOne="tableDatasOne"
        :tableDataTwo="tableDatasTwo"
        ref="childComponentRef"/>
  </el-drawer>
</template>

<style scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>